import router from "@src/router";
import base from "@src/store/base";
import location from "@src/store/location";
import {
  activateCard
} from "@src/api/member";
import {
  getMercFlowConsume,
  getRemindFlag
} from "@src/api/marketing";
import $cache from "@src/common/wxCache";
import config from "@src/config";
import {
  _login
} from "/common/login.js";
import {
  getQrcodeMsg
} from '@src/api/mall/store'

App({
  $router: router,
  globalData: {
    tabParams: null,
    dinnerType: 0,
    dinnerShopid: "",
    dinnerTabNum: "",
    storeAboutQuery: null,
    isNavMini: false, // 是否从小程序跳转过来
    isNavCard: false, // 是否跳转了小程序卡券页面
    extraData: {},
    screenWidth: 0,
    screenHeight: 0,
    marketingUUID: ''
  },
  toFullUrl(value) {
    if (!value) {
      return;
    }
    let fileBaseUrl = this.globalData.extConfig.fileBaseUrl;
    if (
      value.startsWith("http") ||
      value.startsWith("/static/") ||
      value.startsWith("data:image")
    ) {
      return value;
    } else {
      if (!value.startsWith("/") && !value.startsWith("..")) {
        value = "/" + value;
      }
      return fileBaseUrl + value;
    }
  },
  onLaunch(options) {
    this.globalData.extConfig = wx.getExtConfigSync();
    base.themeConfig();
    location.checkAuth();
    if (config.tpl !== 'mall') {
      setTimeout(() => {
        base.initReady();
      }, 2500);
    }
    console.log(`----环境变量=${config.NODE_ENV}-----`);

    this.checkUpdateVersion();
    wx.removeStorageSync('Private_Domain_Meal_Method')
    // 流量交互
    let appId = this.globalData.extConfig.appId
    let businessId = this.globalData.extConfig.businessId
    this.getRemindFlagFun(appId,businessId)
    
    // 获取屏幕宽高
    wx.getSystemInfo({
      success: res => {
        console.log(res)
        this.globalData.screenWidth = res.screenWidth;
        this.globalData.screenHeight = res.screenHeight;
        console.log(64, this.globalData.screenHeight);
      },
      fail(err) {
        console.log(err);
      }
    })
    console.log(`----环境变量=${config.NODE_ENV}-----`);
  },

  async onShow(options) {
    // if(this.globalData.isNavCard && (options.scene === 1037 || options.scene === 1038)) {
    //  return wx.showModal({
    //     title: '提示',
    //     showCancel: false,
    //     content: '操作成功',
    //     success: () => {
    //       wx.exitMiniProgram()
    //     }
    //   })
    // }
    let extraData = options.referrerInfo.extraData;

    // 从开卡组件返回, 调用后端接口激活微信会员卡
    let {
      referrerInfo
    } = options;
    if (extraData ?.miniProgram) {
      // this.globalData.miniProgram = extraData.miniProgram || {}
      this.globalData.extraData = extraData.miniProgram;
      this.globalData.isNavMini = true;
      await $cache.setSync("miniProgram", extraData.miniProgram);
    }
    //全局续token
    // console.log("检查登录态");
    // _login();
    location.checkAuth();
    if (options.query) {
      if (options.query.GLOBAL_SHOP_ID) {
        this.globalData.GLOBAL_SHOP_ID = options.query.GLOBAL_SHOP_ID;
      }
      if (options.query.GLOBAL_PROMOTER_ID) {
        this.globalData.GLOBAL_PROMOTER_ID = options.query.GLOBAL_PROMOTER_ID;
      }
      console.info("this.globalData", this.globalData);
    }

    if (referrerInfo && referrerInfo.appId === "wxeb490c6f9b154ef9") {
      if (referrerInfo.extraData && referrerInfo.extraData.activate_ticket) {
        let data = {
          activateTicket: referrerInfo.extraData.activate_ticket,
          cardId: referrerInfo.extraData.card_id,
          code: referrerInfo.extraData.code,
        };
        // 开卡回来不能用跳回小程序api，因为跳去开卡是跳转小程序的api跳过去的
        activateCard(data).then(res => {})
      } else {}
    }
  },
  onHide() {
    // 其他小程序传来的数据
    // $cache.del('miniProgram')
    this.globalData.isNavMini = false;
  },
  onError(e) {
    console.log("有错误", e);
  },
  onPageNotFound: function (res) {
    let redirectPath = router.checkRenamePath(res.path);

    if (redirectPath && redirectPath !== res.path) {
      router.redirectTo({
        path: redirectPath,
        params: res.query,
      });
      return;
    }
    // 已修改的路径重定向
    wx.showModal({
      title: "温馨提示",
      content: `页面不存在(${res.path})`,
      confirmText: "回首页",
      showCancel: false,
      success(res) {
        if (res.confirm) {
          wx.switchTab({
            url: "/pages/index/main",
          });
        }
      },
    });
  },
  checkUpdateVersion() {
    if (wx.getUpdateManager()) {
      const updateManager = wx.getUpdateManager();
      updateManager.onUpdateReady(function () {
        wx.showModal({
          title: "新版本已经准备好",
          content: "立即重启更新",
          showCancel: false,
          success(res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate();
            }
          },
        });
      });
      updateManager.onUpdateFailed(function () {
        // 新版本下载失败
        wx.showToast({
          title: "新版本下载失败,请手动更新",
          icon: "none",
          duration: 6000,
        });
      });
    } else {
      //TODO 此时微信版本太低（一般而言版本都是支持的）
      // wx.showModal({
      //   title: '溫馨提示',
      //   content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      // })
    }
  },
  // 流量消耗
  mercFlowConsumeFun(appId) {
    let phone = $cache.get("base_info").phone;
    getMercFlowConsume({
      phone: phone ? phone : "",
      appId: appId,
    }).then((res) => {
      if (res.data) {
        wx.showModal({
          title: "提示",
          showCancel: false,
          content: res.data,
          success: function (res) {
            if (res.confirm) {
              wx.exitMiniProgram();
            } else {
              wx.exitMiniProgram();
            }
          },
        });
      }
    });
  },
  // 流量提示
  getRemindFlagFun(appId, businessId) {
    getRemindFlag({
      businessId: businessId,
    }).then((res) => {
      if (res.data) {
        wx.showModal({
          title: "提示",
          showCancel: false,
          content: res.data,
          success: function (res) {
            if (res.confirm) {
              wx.exitMiniProgram();
            } else {
              wx.exitMiniProgram();
            }
          },
        });
      } else {
        this.mercFlowConsumeFun(appId);
      }
    });
  },
});